"ui";
var color = "#009688";
ui.layout(
<vertical>
    <frame w="*" h="auto">
        <webview id="webView" layout_below="title" />
    </frame>
</vertical>
);

ui.webView.webViewClient = new JavaAdapter(android.webkit.WebViewClient, {
    onPageFinished: (webView, curUrl)=>{
        // 加载bridge
        let js = files.read("bridge.js");
        webView.loadUrl("javascript:" + js);
    },
    shouldOverrideUrlLoading: (webView, curUrl) => {
        try {
            let uris = curUrl.a.a.split("/");
            if (uris[0] == "jsbridge:") {
                let cmd = uris[2];
                let callId = uris[3];
                let params = java.net.URLDecoder.decode(uris[4], "UTF-8");
                console.log('安卓接收到JavaScript调用请求: callId=%s, cmd=%s, params=%s', callId, cmd, params);
                let result = cmdAction(cmd, params);
                if (result) {
                    webView.loadUrl("javascript:window.Android.callback({'callId':" + callId + ", 'params': " + JSON.stringify(result) + "});");
                }
                return false;
            } else {
                webView.loadUrl(curUrl.a.a);
            }
            return true;
        } catch(e) {
            console.error(e);
        }
    }
});
ui.webView.webChromeClient = new JavaAdapter(android.webkit.WebChromeClient, {
    onConsoleMessage: (msg) => {
        console.log("[%s:%s]: %s", msg.sourceId(), msg.lineNumber(), msg.message());
    }
});

/**
 * 命令调度
 * @param {命令} cmd 
 * @param {参数} params 
 */
function cmdAction(cmd, params) {
    console.log('处理 cmd = ' + cmd + ', params=' + params);
    switch (cmd) {
        case 'toastCallback':
            return doToastCallback(params);
        case 'toastNoCallback':
            return doToastNoCallback(params);
        default:
            toast('不支持 cmd:' + cmd);
    }
}

/**
 * 具体命令执行入口
 * @param {参数} params 
 */
function doToastCallback(params) {
    toast(JSON.parse(params).msg);
    return {msg: 'toast提示成功'};
}
function doToastNoCallback(params) {
    toast(JSON.parse(params).msg);
}


// ui.webView.loadUrl("https://www.baidu.com/");
ui.webView.loadUrl("https://github.com/710850609/autojs-webView");
/**
 * 模拟JavaScript调用安卓
 * 两端统一好 cmd、params格式、callback的params 格式
 */ 
setTimeout(() => {
    ui.webView.loadUrl("javascript:window.Android.invoke('toastCallback', {msg: '有回调'}, (data) => {console.log('接收到callback:' + JSON.stringify(data));});");
    ui.webView.loadUrl("javascript:window.Android.invoke('toastCallback', {msg: '有回调'}, (data) => {console.log('接收到callback:' + JSON.stringify(data));});");
    ui.webView.loadUrl("javascript:window.Android.invoke('toastCallback', {msg: '有回调'}, (data) => {console.log('接收到callback:' + JSON.stringify(data));});");
    setTimeout(()=>{
        ui.webView.loadUrl("javascript:window.Android.invoke('toastNoCallback', {msg: '无回调'}, (data) => {console.log('接收到callback:' + JSON.stringify(data));});");
    }, 2000);
}, 2000);